package nc.bs.cmp.pub.eventlistenerforsettle;

import java.util.HashMap;
import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.cmp.pub.eventlistenerforsettle.CmpSendSettleFieldCheckListener;
import nc.bs.cmp.util.CmpBillPubUtil;
import nc.bs.framework.common.NCLocator;
import nc.pubitf.cmp.paybill.ICmpPayBillPubQueryService;
import nc.vo.cmp.bill.BillAggVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.UFDate;
import nc.vo.sp.commissionpaysettle.AggCommissionPaySettleVO;
import nc.vo.sp.commissionpaysettle.CommissionPaySettleVO;
import nc.vo.sp.paysettle.AggPaySettleVO;
import nc.vo.sp.paysettle.PaySettleVO;
import nc.vo.sp.settle.CombineFlagEnum;
import nc.vo.tmpub.util.ArrayUtil;
import nc.vo.tmpub.util.ModuleEnum;

public class CmpSendSettleFieldCheckListener implements IBusinessListener {
	public void doAction(IBusinessEvent event) throws BusinessException {
		Object obj = null;
		if (event instanceof BdUpdateEvent) {
			obj = ((BdUpdateEvent.BDUpdateUserObj) event.getUserObject()).getNewObj();
		} else {
			obj = ((BusinessEvent.BusinessUserObj) event.getUserObject()).getUserObj();
		}
		HashMap<String, Object[]> destFieldValues = null;
		if (obj.getClass().isArray()) {
			Object[] object = (Object[]) obj;
			String billPk = null;
			if (ArrayUtil.isNull(object))
				return;
			if (object[0] instanceof AggCommissionPaySettleVO settleAggVO) {
                CommissionPaySettleVO settleParentVO = settleAggVO.getParentVO();
				String srcSystem = settleParentVO.getSrc_system();
				if (!ModuleEnum.CMP.getSysCode().toUpperCase().equals(srcSystem))
					return;
				billPk = settleParentVO.getSrc_pkbill();
				destFieldValues = getDestFieldValues(settleAggVO, commissionDestfields,
						"src_pkdetail");
			} else if (object[0] instanceof AggPaySettleVO settleAggVO) {
                PaySettleVO settleParentVO = (PaySettleVO) settleAggVO.getParentVO();
				if (settleParentVO.getCombineflag() != null
						&& CombineFlagEnum.COMBINEGEN.toIntValue() == settleParentVO.getCombineflag().intValue())
					return;
				String srcSystem = settleParentVO.getSystemcode();
				if (!ModuleEnum.CMP.getSysCode().toUpperCase().equals(srcSystem))
					return;
				billPk = settleParentVO.getPk_srcbill();
				destFieldValues = getDestFieldValues(settleAggVO, payDestfields,
						"pk_billdetail");
			}
			BillAggVO[] aggvos = null;
			ICmpPayBillPubQueryService service = NCLocator.getInstance()
					.lookup(ICmpPayBillPubQueryService.class);
			try {
				aggvos = service.findBillByPrimaryKey(new String[] { billPk });
			} catch (Exception e) {
				throw new BusinessException(e);
			}
			if (ArrayUtil.isNull(aggvos))
				return;
			if (object[0] instanceof AggPaySettleVO)
				CmpBillPubUtil.validatePaySettleBusitype(aggvos);
			StringBuffer msg1 = compareFields(aggvos[0], destFieldValues);
			StringBuilder errMsg = new StringBuilder();
			if (!"".contentEquals(msg1)) {
				msg1.setCharAt(msg1.length() - 1, ' ');
				errMsg.append(msg1).append("\n\n");
			}
			if (!"".contentEquals(errMsg))
				throw new BusinessException(errMsg.toString());
		}
	}

	public static String[] payDestfields = new String[] { "pk_currtype_busi", "pay_busi", "pk_trader", "pk_oppaccount",
			"oppaccname" };

	public static String[] commissionDestfields = new String[] { "pk_busicurr", "busimny", "pk_recunit",
			"pk_recaccount", "recaccountname" };

	private HashMap<String, Object[]> getDestFieldValues(AggregatedValueObject destagg, String[] destFields,
			String srcPKField) {
		HashMap<String, Object[]> valueMap = new HashMap<>();
		CircularlyAccessibleValueObject[] destChildrenVOs = destagg.getChildrenVO();
		Object destFieldValue = null;
		byte b;
		int i;
		CircularlyAccessibleValueObject[] arrayOfCircularlyAccessibleValueObject1;
		for (i = (arrayOfCircularlyAccessibleValueObject1 = destChildrenVOs).length, b = 0; b < i;) {
			CircularlyAccessibleValueObject destChildrenVO = arrayOfCircularlyAccessibleValueObject1[b];
			Object[] value = new Object[destFields.length];
			for (int j = 0; j < destFields.length; j++) {
				destFieldValue = destChildrenVO.getAttributeValue(destFields[j]);
				if (destFieldValue == null) {
					value[j] = "";
				} else {
					value[j] = destFieldValue;
				}
			}
			valueMap.put((String) destChildrenVO.getAttributeValue(srcPKField), value);
			b++;
		}
		return valueMap;
	}

	private StringBuffer compareFields(AggregatedValueObject srcagg, HashMap<String, Object[]> valueMap) {
		StringBuffer msg1 = new StringBuffer();
		String[][] srcfields = {
				{ "pk_currtype", NCLangRes4VoTransl.getNCLangRes().getStrByID("3607mng_0", "03607mng-0469") },
				{ "pay_primal", NCLangRes4VoTransl.getNCLangRes().getStrByID("3607mng_0", "03607mng-0470") },
				{ "pk_trader", NCLangRes4VoTransl.getNCLangRes().getStrByID("3607mng_0", "03607mng-0471") },
				{ "pk_account", NCLangRes4VoTransl.getNCLangRes().getStrByID("3607mng_0", "03607mng-0472") } };
		CircularlyAccessibleValueObject[] srcChildrenVOs = srcagg.getChildrenVO();
		Object result = null;
		Object srcField = null;
		byte b;
		int i;
		CircularlyAccessibleValueObject[] arrayOfCircularlyAccessibleValueObject1;
		for (i = (arrayOfCircularlyAccessibleValueObject1 = srcChildrenVOs).length, b = 0; b < i;) {
			CircularlyAccessibleValueObject srcChildVO = arrayOfCircularlyAccessibleValueObject1[b];
			Object[] destFieldValues = valueMap.get(srcChildVO.getAttributeValue("pk_paybill_detail"));
			for (int j = 0; j < srcfields.length; j++) {
				String[] field = srcfields[j];
				if (!"pk_trader".equals(field[0])) {
					srcField = srcChildVO.getAttributeValue(field[0]);
					result = compareField(srcField, destFieldValues[j]);
					if (result != null) {
						addMsg(msg1, field[1]);
						break;
					}
				} else if (srcChildVO.getAttributeValue("objecttype") != null) {
					Integer type = Integer.valueOf(srcChildVO.getAttributeValue("objecttype").toString());
					if (type.intValue() == 0) {
						srcField = srcChildVO.getAttributeValue("pk_customer");
					} else if (1 == type.intValue()) {
						srcField = srcChildVO.getAttributeValue("pk_supplier");
					} else if (2 == type.intValue()) {
						srcField = srcChildVO.getAttributeValue("pk_dept");
					} else if (3 == type.intValue()) {
						srcField = srcChildVO.getAttributeValue("pk_busiman");
					} else if (4 == type.intValue()) {
						srcField = (srcChildVO.getAttributeValue("pk_customer") == null)
								? srcChildVO.getAttributeValue("pk_supplier")
								: srcChildVO.getAttributeValue("pk_customer");
					}
					result = compareField(srcField, destFieldValues[j]);
					if (result != null) {
						addMsg(msg1, field[1]);
						break;
					}
				}
			}
			b++;
		}
		return msg1;
	}

	private void addMsg(StringBuffer msg, String string) {
		if ("".contentEquals(msg))
			msg.append(NCLangRes4VoTransl.getNCLangRes().getStrByID("3607mng_0", "03607mng-0474"));
		msg.append(string + ",");
	}

	private Object compareField(Object oldField, Object newField) {
		Object result = null;
		if (oldField == null && newField == null) {
			result = null;
		} else if (oldField == null || newField == null) {
			Object tmp = (oldField == null) ? newField : oldField;
			if (tmp instanceof String && "".equals(tmp))
				tmp = null;
			result = tmp;
		} else if (oldField instanceof UFDate) {
			if (newField instanceof UFDate) {
				result = ((UFDate) oldField).isSameDate((UFDate) newField) ? null : oldField;
			} else {
				result = oldField;
			}
		} else {
			result = newField.equals(oldField) ? null : oldField;
		}
		return result;
	}
}
